//
//  CJRewardView.swift
//  CJBookReader
//
//  Created by lidi on 2017/11/30.
//  Copyright © 2017年 lidi. All rights reserved.
//

import UIKit

//打赏界面
class CJRewardView: UIView {

    var reChargeHandle:(()->Void)?
    
    private lazy var contentView = UIView()
    
    private lazy var labelPrice = UILabel()
    private lazy var buttonPay = UIButton(type: .custom)
    
    private var rewardViewHeight:CGFloat = 0
    
    private var balance = 0 //余额
    private var txtBookId = ""
    
    private var priceCells = [PriceCell]()
    private var selectedPrice = 0 {
        didSet {
            
            let attrText = NSMutableAttributedString()
            if self.balance >= self.selectedPrice {
                //钱够
                attrText.append(NSAttributedString(string: "打赏:", attributes: [.font:UIFont.systemFont(ofSize: 13.0), .foregroundColor:UIColor.lightGray]))
                attrText.append(NSAttributedString(string: " \(self.selectedPrice)长江币", attributes: [.font:UIFont.systemFont(ofSize: 13.0), .foregroundColor:UIColor.cj.red]))
                
                self.buttonPay.setTitle("确认", for: .normal)
                
            } else {
                //不足
                attrText.append(NSAttributedString(string: "当前余额不足，请先充值", attributes: [.font:UIFont.systemFont(ofSize: 13.0), .foregroundColor:UIColor.cj.red]))
                
                self.buttonPay.setTitle("充值", for: .normal)

            }
            
            self.labelPrice.attributedText = attrText
        }
    }
    
    
    init(txtBookId:String,balance:Int,reChargeHandle:(()->Void)?) {
        super.init(frame: CGRect.zero)
        
        self.txtBookId = txtBookId
        self.balance = balance
        self.reChargeHandle = reChargeHandle
        
        let maskView = UIView()
        self.addSubview(maskView)
        maskView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        maskView.isUserInteractionEnabled = true
        let closeTap = UITapGestureRecognizer(target: self, action: #selector(self.close))
        maskView.addGestureRecognizer(closeTap)
        
        //底部
        self.rewardViewHeight += 50.0
        
        let bottomView = UIView()
        bottomView.backgroundColor = UIColor.white
        self.contentView.addSubview(bottomView)
        bottomView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(50.0)
        }
        
        self.labelPrice.font = UIFont.systemFont(ofSize: 14.0)
        bottomView.addSubview(self.labelPrice)
        self.labelPrice.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15.0)
            make.centerY.equalToSuperview()
        }
        
        self.buttonPay.setTitle("确认", for: .normal)
        self.buttonPay.backgroundColor = UIColor.cj.red
        self.buttonPay.setTitleColor(UIColor.white, for: .normal)
        self.buttonPay.layer.cornerRadius = 2.0
        self.buttonPay.layer.masksToBounds = true
        self.buttonPay.titleLabel?.font = UIFont.systemFont(ofSize: 15.0)
        self.buttonPay.addTarget(self, action: #selector(self.pay), for: .touchUpInside)
        bottomView.addSubview(self.buttonPay)
        self.buttonPay.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-25.0)
            make.centerY.equalToSuperview()
            make.width.equalTo(90.0)
            make.height.equalTo(35.0)
        }
        
        //中间打赏积分部分
        let prices = [98,188,388,588,1888,5888,8888,18888,88888]
        
        let height:CGFloat = 50.0
        let columnCount = 3
        let distance:CGFloat = 10.0
        let margin:CGFloat = 15.0
        
        let width = (UIScreen.main.width - margin * 2 - distance * CGFloat(columnCount - 1)) / CGFloat(columnCount)
        let rowCount = prices.count % columnCount == 0 ? prices.count / columnCount : prices.count / columnCount + 1
        
        let priceContainer = UIView()
        priceContainer.backgroundColor = UIColor(red: 245.0 / 255.0, green: 248.0 / 255.0, blue: 250.0 / 255.0, alpha: 1)
        self.contentView.addSubview(priceContainer)
        
        var x = margin
        var y = margin
        
        for row in 0 ..< rowCount {
            for column in 0 ..< columnCount {
                let index = columnCount * row + column
                if index < prices.count {
                    let price = prices[index]
                    let priceCell = PriceCell(price: price)
                    
                    priceCell.isUserInteractionEnabled = true
                    let priceTap = UITapGestureRecognizer(target: self, action: #selector(self.choosePrice(sender:)))
                    priceCell.addGestureRecognizer(priceTap)
                    
                    priceContainer.addSubview(priceCell)
                    priceCell.snp.makeConstraints({ (make) in
                        make.left.equalToSuperview().offset(x)
                        make.top.equalToSuperview().offset(y)
                        make.width.equalTo(width)
                        make.height.equalTo(height)
                    })
                    self.priceCells.append(priceCell)
                }
                
                if (column + 1) % columnCount == 0 {
                    x = margin
                    y += distance + height
                } else {
                    x += distance + width
                }
            }
        }
        
        let totalHeight = margin * 2 + CGFloat(rowCount) * height + CGFloat(rowCount - 1) * distance
        self.rewardViewHeight += totalHeight

        priceContainer.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(totalHeight)
            make.bottom.equalTo(bottomView.snp.top)
        }
        
        //头部
        self.rewardViewHeight += 44.0

        let topView = UIView()
        topView.backgroundColor = UIColor.white
        self.contentView.addSubview(topView)
        topView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(priceContainer.snp.top)
            make.height.equalTo(44.0)
        }
        
        let line = UIView()
        line.backgroundColor = UIColor.lightGray
        topView.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(0.5)
        }
        
        //关闭
        let buttonClose = UIButton(type: .custom)
        buttonClose.setImage(UIImage(named: "button_close", in: Bundle(for: type(of: self)), compatibleWith: nil), for: .normal)
        buttonClose.addTarget(self, action: #selector(self.close), for: .touchUpInside)
        topView.addSubview(buttonClose)
        buttonClose.snp.makeConstraints { (make) in
            make.top.right.bottom.equalToSuperview()
            make.width.equalTo(44.0)
        }

        let labelTitle = UILabel()
        labelTitle.text = "打赏"
        labelTitle.textAlignment = .center
        topView.addSubview(labelTitle)
        labelTitle.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
        }
        
        self.addSubview(self.contentView)
        self.contentView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(self.rewardViewHeight)
            make.bottom.equalToSuperview().offset(self.rewardViewHeight)
        }
    }
    
    func show() {
        
        //默认选中第一个价格
        if let priceCell = self.priceCells.first {
            priceCell.isSelected = true
            self.selectedPrice = priceCell.price
        }
        
        UIApplication.shared.keyWindow?.addSubview(self)
        self.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        self.layoutIfNeeded()

        self.contentView.snp.updateConstraints { (make) in
            make.bottom.equalToSuperview()
        }
        
        UIView.animate(withDuration: 0.3, animations: { [weak self] in
            self?.layoutIfNeeded()
        }, completion: nil)
    }
    
    @objc private func close() {
        self.contentView.snp.updateConstraints { (make) in
            make.bottom.equalToSuperview().offset(self.rewardViewHeight)
        }
        UIView.animate(withDuration: 0.3, animations: { [weak self] in
            self?.layoutIfNeeded()
            }, completion: { [weak self] (finish) in
                self?.removeFromSuperview()
        })
    }
    
    @objc private func choosePrice(sender:UIGestureRecognizer?) {
        if let priceCell = sender?.view as? PriceCell {
            for item in self.priceCells {
                item.isSelected = false
            }
            
            priceCell.isSelected = true
            self.selectedPrice = priceCell.price
        }
    }
    
    @objc private func pay() {
        
        self.close()
        
//        if self.balance >= self.selectedPrice {
//            //购买
//            MBProgressHUD.showMessage()
//            
//            _ = Router._rewardBook(book_id: self.txtBookId, amount: "\(self.selectedPrice)").request({(response:YLLResponse<JSONObject>) in
//
//                MBProgressHUD.hide()
//
//                if case .success(_,let message) = response {
//                    MBProgressHUD.showSuccess(message)
//                }
//
//                if case .failure(let message,_) = response {
//                    MBProgressHUD.showError(message)
//                }
//            })
//
//        } else {
//            //跳转充值
//            self.reChargeHandle?()
//        }
        
    }
    
    class PriceCell: UIView {
        
        var price = 0
        
        init(price:Int) {
            super.init(frame: CGRect.zero)
            
            self.price = price
            
            let labelPrice = UILabel()
            labelPrice.font = UIFont.systemFont(ofSize: 16.0)
            labelPrice.textColor = UIColor.darkGray
            labelPrice.text = "\(price)"
            self.addSubview(labelPrice)
            labelPrice.snp.makeConstraints { (make) in
                make.top.equalToSuperview().offset(7.0)
                make.centerX.equalToSuperview()
            }
            
            let labelPriceUnit = UILabel()
            labelPriceUnit.font = UIFont.systemFont(ofSize: 11.0)
            labelPriceUnit.textColor = UIColor.lightGray
            labelPriceUnit.text = "长江币"
            self.addSubview(labelPriceUnit)
            labelPriceUnit.snp.makeConstraints { (make) in
                make.bottom.equalToSuperview().offset(-7.0)
                make.centerX.equalToSuperview()
            }
            
            self.backgroundColor = UIColor.white
            self.layer.borderColor = UIColor.lightGray.cgColor
            self.layer.borderWidth = 0.5
        }
        
        var isSelected = false {
            didSet {
                if oldValue != self.isSelected {
                    if self.isSelected {
                        self.layer.borderColor = UIColor.cj.red.cgColor
                    } else {
                        self.layer.borderColor = UIColor.lightGray.cgColor
                    }
                }
            }
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
